package org.light.complexverb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.generator.NamedStatementListGenerator;
import org.light.oracle.generator.MybatisOracleSqlReflector;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class ListMyActive extends TwoDomainVerb{

	@Override
	public Method generateDaoImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(this.getVerbName()));
		method.setNoContainer(false);
		method.addSignature(new Signature(1, "db","*sql.DB"));
		method.addSignature(new Signature(2, this.master.getLowerFirstDomainName()+"Id",this.master.getDomainId().getFieldType()));
		method.setReturnType(new Type("[] "+this.slave.getDomainSuffix()+"."+this.slave.getType()));
		
		List<Writeable> sList = new ArrayList<Writeable>();
		
		if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
			sList.add(new Statement(1000L,1,"sql := \""+MybatisSqlReflector.generateSelectActiveUsingMasterIdStatement(master,slave)+"\""));
		} else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
			sList.add(new Statement(1000L,1,"sql := \""+PgsqlReflector.generateSelectActiveUsingMasterIdStatement(master,slave)+"\""));
		} else if (this.getDbType().equalsIgnoreCase("Oracle")) {
			sList.add(new Statement(1000L,1,"sql := \""+MybatisOracleSqlReflector.generateSelectActiveUsingMasterIdStatement(master,slave)+"\""));
		}
		
		sList.add(new Statement(2000L,1,"stmt, err := db.Prepare(sql)"));
		sList.add(new Statement(2500L,1,"defer stmt.Close()"));
		sList.add(new Statement(3000L,1,"if err != nil {"));
		sList.add(new Statement(4000L,2,"panic(err)"));
		sList.add(new Statement(5000L,1,"}"));
		sList.add(new Statement(6000L,1,"rows, err := stmt.Query("+this.master.getLowerFirstDomainName()+"Id)"));
		sList.add(new Statement(7000L,1,"if err != nil {"));
		sList.add(new Statement(8000L,2,"panic(err)"));
		sList.add(new Statement(9000L,1,"}"));
		sList.add(new Statement(10000L,1,""+this.slave.getLowerFirstPlural()+" := [] "+this.slave.getDomainSuffix()+"."+this.slave.getCapFirstDomainNameWithSuffix()+"{}"));
		sList.add(new Statement(11000L,0,""));
		sList.add(new Statement(12000L,1,"for rows.Next() {"));
		
		StringBuilder sb = new StringBuilder();
		if (this.slave.getDomainId()!=null) sList.add(new Statement(13000L,2,"var "+this.slave.getDomainId().getLowerFirstFieldName()+" "+ this.slave.getDomainId().getFieldTypeWithParseImage()));
		if (this.slave.getDomainName()!=null) sList.add(new Statement(14000L,2,"var "+this.slave.getDomainName().getLowerFirstFieldName()+" "+ this.slave.getDomainName().getFieldTypeWithParseImage()));
		if (this.slave.getActive()!=null) sList.add(new Statement(15000L,2,"var "+this.slave.getActive().getLowerFirstFieldName()+" "+ this.slave.getActive().getFieldTypeWithParseImage()));
		
		if (this.slave.getDomainId()!=null) sb.append("&").append(this.slave.getDomainId().getLowerFirstFieldName()).append(",");
		if (this.slave.getDomainName()!=null) sb.append("&").append(this.slave.getDomainName().getLowerFirstFieldName()).append(",");
		if (this.slave.getActive()!=null) sb.append("&").append(this.slave.getActive().getLowerFirstFieldName()).append(",");
		
		long serial = 17000L;
		for (Field f:this.slave.getSearchPlainFields()) {
			if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.master.getDbType())){
				sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" NullString"));
				sb.append("&").append(f.getLowerFirstFieldName()).append(",");
				serial += 1000L;
				continue;
			}
			sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldNullTypeWithParseImage()));
			sb.append("&").append(f.getLowerFirstFieldName()).append(",");
			serial += 1000L;
		}
		String fieldsQuery = sb.toString();
		if (fieldsQuery.endsWith(",")) fieldsQuery = fieldsQuery.substring(0,fieldsQuery.length()-1);
		sList.add(new Statement(serial,0,""));
		sList.add(new Statement(serial+1000L,2,"err := rows.Scan("+fieldsQuery+")"));
		sList.add(new Statement(serial+2000L,2,"if err != nil {"));
		sList.add(new Statement(serial+3000L,3,"panic(err)"));
		sList.add(new Statement(serial+4000L,2,"}"));
		sList.add(new Statement(serial+5000L,2,"var "+this.slave.getLowerFirstDomainName()+" "+this.slave.getDomainSuffix()+"."+this.slave.getCapFirstDomainNameWithSuffix()+""));
		
		if (this.slave.getDomainId()!=null) sList.add(new Statement(serial+6000L,2,""+this.slave.getLowerFirstDomainName()+".Set"+this.slave.getDomainId().getCapFirstFieldName()+"("+this.slave.getDomainId().getLowerFirstFieldName()+")"));
		if (this.slave.getDomainName()!=null) sList.add(new Statement(serial+7000L,2,""+this.slave.getLowerFirstDomainName()+".Set"+this.slave.getDomainName().getCapFirstFieldName()+"("+this.slave.getDomainName().getLowerFirstFieldName()+")"));
		if (this.slave.getActive()!=null) sList.add(new Statement(serial+8000L,2,""+this.slave.getLowerFirstDomainName()+".Set"+this.slave.getActive().getCapFirstFieldName()+"("+this.slave.getActive().getLowerFirstFieldName()+")"));
		serial += 9000L;
		for (Field f:this.slave.getSearchPlainFields()) {
			if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.master.getDbType())){
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullStringtoInt64("+f.getLowerFirstFieldName()+"))"));
				serial += 1000L;
				continue;
			}
			switch (f.getFieldType()) {
			case "bool": 
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullBool("+f.getLowerFirstFieldName()+"))"));
				break;
			case "string": 
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullString("+f.getLowerFirstFieldName()+"))"));
				break;
			case "int64": 
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt64("+f.getLowerFirstFieldName()+"))"));
				break;
			case "float64": 
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullFloat64("+f.getLowerFirstFieldName()+"))"));
				break;
			case "int32": 
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt32("+f.getLowerFirstFieldName()+"))"));
				break;
			default:
				sList.add(new Statement(serial,2,""+this.slave.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
			}
			serial += 1000L;
		}
		sList.add(new Statement(serial,2,""+this.slave.getLowerFirstPlural()+" = append("+this.slave.getLowerFirstPlural()+", "+this.slave.getLowerFirstDomainName()+")"));
		sList.add(new Statement(serial,1,"}"));
		sList.add(new Statement(serial+1000L,1,"return "+this.slave.getLowerFirstDomainName()+"s"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(this.getVerbName()));
		method.setReturnType(new Type("[] "+this.slave.getDomainSuffix()+"."+this.slave.getType()));
		method.addSignature(new Signature(1, "db","*sql.DB"));
		method.addSignature(new Signature(2,this.master.getLowerFirstDomainName()+"Id",this.master.getDomainId().getClassType()));
		method.setThrowException(true);
		return method;
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(this.getVerbName()));
		method.setReturnType(new Type("[] "+this.slave.getDomainSuffix()+"."+this.slave.getType()));
		method.addSignature(new Signature(1,this.master.getLowerFirstDomainName()+"Id", this.master.getDomainId().getClassType()));
		method.setThrowException(true);
		return method;
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(this.getVerbName()));		
		method.setReturnType(new Type("[] "+this.slave.getDomainSuffix()+"."+this.slave.getType()));
		method.addSignature(new Signature(1,this.master.getLowerFirstDomainName()+"Id", this.master.getDomainId().getClassType()));
		
		Method daomethod = this.generateDaoMethodDefinition();
		
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(new Statement(1000L,1,"db := database.DB"));
		list.add(NamedStatementListGenerator.generateServiceImplReturnList(2000L, 1, this.master,
				this.master.getDaoimplSuffix(), daomethod));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}
	@Override
	public Method generateControllerMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(this.getVerbName()));		
		method.addSignature(new Signature(1,"c","*gin.Context"));
		
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,1,"idStr := c.PostForm(\""+this.master.getLowerFirstDomainName()+"Id\")"));
		sList.add(new Statement(2000L,1,this.master.getLowerFirstDomainName()+"Id, _ := strconv.ParseInt(idStr, 10, 64)"));
		sList.add(new Statement(3000L,1,this.slave.getLowerFirstPlural()+" := []"+this.slave.getDomainSuffix()+"."+this.slave.getCapFirstDomainNameWithSuffix()+"{}"));
		sList.add(new Statement(4000L,1,"if "+this.master.getLowerFirstDomainName()+"Id > 0 {"));
		sList.add(new Statement(5000L,2,this.slave.getLowerFirstPlural()+" = "+this.master.getServiceimplSuffix()+"."+StringUtil.capFirst(this.getVerbName())+"("+this.master.getLowerFirstDomainName()+"Id)"));
		sList.add(new Statement(6000L,1,"}"));
		sList.add(new Statement(7000L,1,"total := len("+this.slave.getLowerFirstPlural()+")"));
		sList.add(new Statement(8000L,1,"SendResponse(c, nil, "+this.slave.getLowerFirstPlural()+", total, true)"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}

	public ListMyActive(Domain master,Domain slave){
		super();
		this.master = master;
		this.slave = slave;
		this.setVerbName("ListActive"+this.master.getCapFirstDomainName()+StringUtil.capFirst(this.slave.getAliasPlural())+"Using"+this.master.getCapFirstDomainName()+"Id");
		this.setLabel("列出所属");
		this.dbType = master.getDbType();
	}

}
